package com.shop.admin.service.impl;

import com.shop.Result.LdbzResult;
import com.shop.admin.service.AdminPicService;
import com.shop.utils.FtpUtil;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class AdminPicServiceImpl implements AdminPicService {
    @Override
    public LdbzResult uploadFile(MultipartFile file, HttpServletRequest request, RedirectAttributes redirectAttributes) throws IOException {
        String originalFilename = file.getOriginalFilename();  //获取到文件的原名称，01.jpg

        // 上传文件以日期为单位分开存放，可以提高图片的查询速度 , 示例：/2022/04/14
        String filePath = "/" + new SimpleDateFormat("yyyy").format(new Date()) + "/"
                + new SimpleDateFormat("MM").format(new Date()) + "/"
                + new SimpleDateFormat("dd").format(new Date());

        Random random = new Random();
        // 新文件名  12837821753332.jpg
        String fileName = System.currentTimeMillis()+String.format("%03d",random.nextInt(999))+
                originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件操作
        boolean isUpload = FtpUtil.uploadFile(
                "192.168.1.100",
                21,
                "ftpuser",
                "wzggxlp2831",
                "/home/ftpuser/www/images/",
                filePath,
                fileName,
                file.getInputStream()
        );

        //String url = "http://192.168.11.100/images/2022/04/14/72235213525.jpg";
        String url = "http://192.168.1.100/images"+filePath +"/"+ fileName;
        System.out.println(url);
        System.out.println(isUpload);
        if (isUpload){
            return LdbzResult.ok(url);
        }
        return LdbzResult.build(500,"上传失败");
    }
}
